import { useState, useEffect } from 'react';

// 定义主题类型
type Theme = 'light' | 'dark' | 'system';

// 主题钩子接口
interface UseThemeReturn {
  theme: Theme;
  toggleTheme: () => void;
};

const useTheme = (): UseThemeReturn => {
  // 从本地存储获取主题，默认为系统主题
  const [theme, setTheme] = useState<Theme>(() => {
    const savedTheme = localStorage.getItem('theme') as Theme | null;
    return savedTheme || 'system';
  });

  // 当主题变化时，更新文档的class和本地存储
  useEffect(() => {
    const root = window.document.documentElement;
    root.classList.remove('light', 'dark');

    let appliedTheme: Theme;

    // 如果是系统主题，则根据系统设置应用
    if (theme === 'system') {
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      appliedTheme = prefersDark ? 'dark' : 'light';
    } else {
      appliedTheme = theme;
    }

    root.classList.add(appliedTheme);
    localStorage.setItem('theme', theme);
  }, [theme]);

  // 切换主题函数
  const toggleTheme = () => {
    setTheme(prev => {
      if (prev === 'light') return 'dark';
      if (prev === 'dark') return 'system';
      return 'light';
    });
  };

  return {
    theme,
    toggleTheme
  };
};

export default useTheme;